package com.app.twth.slidingmenu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.lifecycle.ViewModelProvider;

import com.airsaid.pickerviewlibrary.OptionsPickerView;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.bean.PdaPassword;
import com.app.twth.databinding.ActivitySlidingBinding;
import com.app.twth.databinding.DialogSkuMultipleHintBinding;
import com.app.twth.databinding.FragmentContentBinding;
import com.app.twth.databinding.FragmentMenuBinding;
import com.app.twth.net.OkHttpUtils;
import com.app.twth.statusbar.ScreenUtils;
import com.app.twth.ui.adjust.AdjustActivity;
import com.app.twth.ui.b2bpick.B2BPickActivity;
import com.app.twth.ui.b2btrailer.B2BTrailerActivity;
import com.app.twth.ui.b2cpick.B2CPickActivity;
import com.app.twth.ui.b2ctrailer.B2CTrailerActivity;
import com.app.twth.ui.b2cverify.B2CVerifyActivity;
import com.app.twth.ui.checkin.CheckinActivity;
import com.app.twth.ui.cyclecount.CycleCountActivity;
import com.app.twth.ui.finalprocess.FinalProcessActivity;
import com.app.twth.ui.login.LoginActivity;
import com.app.twth.ui.login.UserEntity;
import com.app.twth.ui.lpnphoto.LPNPhotoActivity;
import com.app.twth.ui.main.MainViewModel;
import com.app.twth.ui.main.TaskQty;
import com.app.twth.ui.main.UserResource;
import com.app.twth.ui.mine.version.UpdateVersion;
import com.app.twth.ui.mine.version.VersionActivity;
import com.app.twth.ui.news.NewsActivity;
import com.app.twth.ui.preprocess.PreprocessActivity;
import com.app.twth.ui.printer.PrinterActivity;
import com.app.twth.ui.putaway.PutawayActivity;
import com.app.twth.ui.returnsputatay.ReturnsPutatayActivity;
import com.app.twth.ui.returnstrailer.ReturnsTrailerActivity;
import com.app.twth.ui.search.SearchActivity;
import com.app.twth.ui.tally.TallyActivity;
import com.app.twth.ui.transfer.TransferActivity;
import com.app.twth.utils.FastJsonUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.PreferencesUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class SlidingActivity extends AppCompatActivity {
    private String TAG = getClass().getSimpleName();
    private ActivitySlidingBinding binding;
    FragmentContentBinding homeBinding;
    FragmentMenuBinding mineBinding;
    private MainViewModel viewModel;
    private Activity mContext;
    private ArrayList<UserEntity.WarehouseListDTO> warehouseList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ActivitySlidingBinding.inflate(getLayoutInflater());
        ScreenUtils.setStatusBarTransparentAndWordsGray(getWindow());
        homeBinding = FragmentContentBinding.bind(binding.content.getRoot());
        mineBinding = FragmentMenuBinding.bind(binding.menu.getRoot());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        initData();
        initListener();
        viewModel.getPermission();
        viewModel.getNewAppInfo();
//        homeBinding.tvNews.setUnreadCount(5);
//        homeBinding.tvTaskPutaway.setUnreadCount(10);
//        homeBinding.tvTaskReturnsPutaway.setUnreadCount(150);
    }

    private void initData() {
        String name = PreferencesUtil.getString(this, Constant.USER_NAME);
        mineBinding.tvName.setText(Utils.getStr(name));
        String locationName = PreferencesUtil.getString(this, Constant.locationName);
        mineBinding.tvLocaion.setText(Utils.getStr(locationName));
        try {
            String locationList = PreferencesUtil.getString(this, Constant.userWarehouseList);
            if (!Utils.isEmpty(locationList)) {
                warehouseList = (ArrayList<UserEntity.WarehouseListDTO>) FastJsonUtil.getObjects(locationList, UserEntity.WarehouseListDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        binding.content.getRoot().setOnClickListener(v -> {
            Log.e("tag", "content:" + binding.slidingmenu.isOpen());
            if (binding.slidingmenu.isOpen()) {
                binding.slidingmenu.toggleMenu();
            }
        });
        mineBinding.tvLocaion.setOnClickListener(v -> {
            if (warehouseList == null || warehouseList.size() == 0) {
                return;
            }
            setPickerView();
        });
        mineBinding.version.setOnClickListener(v -> {
//            AppRouter.showFragmentActivity(this, ScanActivity.class);
            AppRouter.showFragmentActivity(this, VersionActivity.class);
        });
        mineBinding.vLogout.setOnClickListener(v -> {
            showLogoutDialog();
        });
        mineBinding.vPrinter.setOnClickListener(v -> {
            AppRouter.showFragmentActivity(this, PrinterActivity.class);
        });
        mineBinding.ivRefresh.setOnClickListener(v -> {
            OkHttpUtils.getInstance(mContext);
        });
        mineBinding.tvPassword.setOnClickListener(v -> {
            String password = mineBinding.tvPassword.getText().toString();
            if (Utils.isEmpty(password)) {
                return;
            }
            if (!password.contains("Admin Password: ")) {
                return;
            }
            ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(password.replace("Admin Password: ", ""));//将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可 cm.getText();//获取粘贴信息
            ToastUtil.showToast("Copy success");
            OkHttpUtils.getInstance(mContext);
        });

        if (PreferencesUtil.getBoolean(mContext, Constant.isManager)) {
            String password_default = PreferencesUtil.getString(mContext, Constant.submit_password);
            if (!Utils.isEmpty(password_default)) {
                String str = "Admin Password: ";//TextView所有字体
                int fstart = str.length();//文本中的关键字
                int fend = fstart + password_default.length();
                SpannableStringBuilder style = new SpannableStringBuilder(str + password_default);
                style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                mineBinding.tvPassword.setText(style);
                mineBinding.layoutPassword.setVisibility(View.VISIBLE);
            } else {
                mineBinding.layoutPassword.setVisibility(View.GONE);
            }
        } else {
            mineBinding.layoutPassword.setVisibility(View.GONE);
        }

        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MainViewModel.class);
        binding.setViewModel(viewModel);

        setAllGone();
        String jsonString = PreferencesUtil.getString(this, "authorize");
        if (Utils.isEmpty(jsonString)) {
            return;
        }
        List<UserResource> data = FastJsonUtil.getObjects(jsonString, UserResource.class);
        if (data == null || data.size() == 0) {
            return;
        }
        setAuthorize(data);
    }

    private void initListener() {
        viewModel.versionLiveData.observe(this, data -> {
            try {
                if (data == null) {
                    return;
                }
                String versionCode = data.getVersion();
                if (versionCode.contains(".")) {
                    versionCode = versionCode.replace(".", "");
                }

                String versionName = Utils.getVersionName(mContext);
                if (versionName.contains(".")) {
                    versionName = versionName.replace(".", "");
                }

                int newCode = Integer.parseInt(versionCode);
                int curCode = Integer.parseInt(versionName);

                if ((newCode > curCode) && data.isUpgrade()) {//有新版本并允许升级
                    viewModel.getApk(data.getUrl(), mContext);
                } else {
                    ToastUtil.showToast("This is the latest version");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        viewModel.fileLiveData.observe(this, data -> {
            setApkFile(data);
        });
        viewModel.UserResourceLiveData.observe(this, data -> {
            if (data == null || data.size() == 0)
                return;

            String jsonString = FastJsonUtil.createJsonString(data);
            PreferencesUtil.putString(this, "authorize", jsonString);
            setAllGone();
            setAuthorize(data);
        });
    }

    public void setAllGone() {
        //INBOUND
        homeBinding.layoutInbound.setVisibility(View.GONE);

        homeBinding.tvReceiving.setVisibility(View.GONE);
        homeBinding.tvTally.setVisibility(View.GONE);
        homeBinding.tvDamage.setVisibility(View.GONE);
        homeBinding.tvLpnPhoto.setVisibility(View.GONE);
        homeBinding.tvPutaway.setVisibility(View.GONE);

        //OUTBOUND
        homeBinding.layoutOutbound.setVisibility(View.GONE);
        homeBinding.tvB2bOutbound.setVisibility(View.GONE);
        homeBinding.tvB2cOutbound.setVisibility(View.GONE);
        homeBinding.vB2bOutbound.setVisibility(View.GONE);
        homeBinding.vB2cOutbound.setVisibility(View.GONE);

        homeBinding.tvB2cPick.setVisibility(View.GONE);
        homeBinding.tvB2cVerify.setVisibility(View.GONE);
        homeBinding.tvB2cTrailer.setVisibility(View.GONE);
        homeBinding.tvB2bPick.setVisibility(View.GONE);
        homeBinding.tvB2bTrailer.setVisibility(View.GONE);

        //RETURNS
        homeBinding.layoutReturns.setVisibility(View.GONE);

        homeBinding.tvPreprocess.setVisibility(View.GONE);
        homeBinding.tvFinalprocess.setVisibility(View.GONE);
        homeBinding.tvReturnsPutaway.setVisibility(View.GONE);
        homeBinding.tvReturnsTrailer.setVisibility(View.GONE);

        //MANAGE
        homeBinding.layoutManage.setVisibility(View.GONE);

        homeBinding.tvCyclecount.setVisibility(View.GONE);
        homeBinding.tvTransfer.setVisibility(View.GONE);
        homeBinding.tvAdjust.setVisibility(View.GONE);

    }

    public void setAuthorize(List<UserResource> authorizeList) {
        for (int i = 0; i < authorizeList.size(); i++) {
            setModulesVisibility(authorizeList.get(i));
        }
    }

    public void setModulesVisibility(UserResource authorize) {
        if (authorize == null) {
            return;
        }
        if (Utils.isEmpty(authorize.getCode())) {
            return;
        }
        if (authorize.getCode().equals(getString(R.string.pda_inbound_check))) {
            homeBinding.layoutInbound.setVisibility(View.VISIBLE);
            homeBinding.tvReceiving.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_inbound_tally))) {
            homeBinding.layoutInbound.setVisibility(View.VISIBLE);
            homeBinding.tvTally.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_inbound_damage))) {
            homeBinding.layoutInbound.setVisibility(View.VISIBLE);
            homeBinding.tvDamage.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_inbound_lpn_photo))) {
            homeBinding.layoutInbound.setVisibility(View.VISIBLE);
            homeBinding.tvLpnPhoto.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_inbound_putaway))) {
            homeBinding.layoutInbound.setVisibility(View.VISIBLE);
            homeBinding.tvPutaway.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_b2c_pick))) {
            if (homeBinding.tvB2cOutbound.getVisibility() == View.VISIBLE) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) homeBinding.tvB2cOutbound.getLayoutParams();
                float weightSum = layoutParams.weight;
                layoutParams.weight = weightSum + 1;
                homeBinding.tvB2cOutbound.setLayoutParams(layoutParams);

                LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) homeBinding.vB2cOutbound.getLayoutParams();
                float weightSum2 = layoutParams2.weight;
                layoutParams2.weight = weightSum2 + 1;
                homeBinding.vB2cOutbound.setLayoutParams(layoutParams2);
            }

            homeBinding.layoutOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.vB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cPick.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_b2c_verify))) {
            if (homeBinding.tvB2cOutbound.getVisibility() == View.VISIBLE) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) homeBinding.tvB2cOutbound.getLayoutParams();
                float weightSum = layoutParams.weight;
                layoutParams.weight = weightSum + 1;
                homeBinding.tvB2cOutbound.setLayoutParams(layoutParams);

                LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) homeBinding.vB2cOutbound.getLayoutParams();
                float weightSum2 = layoutParams2.weight;
                layoutParams2.weight = weightSum2 + 1;
                homeBinding.vB2cOutbound.setLayoutParams(layoutParams2);
            }

            homeBinding.layoutOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.vB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cVerify.setVisibility(View.VISIBLE);
        }  else if (authorize.getCode().equals(getString(R.string.pda_outbound_b2c_trailer))) {
            if (homeBinding.tvB2cOutbound.getVisibility() == View.VISIBLE) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) homeBinding.tvB2cOutbound.getLayoutParams();
                float weightSum = layoutParams.weight;
                layoutParams.weight = weightSum + 1;
                homeBinding.tvB2cOutbound.setLayoutParams(layoutParams);

                LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) homeBinding.vB2cOutbound.getLayoutParams();
                float weightSum2 = layoutParams2.weight;
                layoutParams2.weight = weightSum2 + 1;
                homeBinding.vB2cOutbound.setLayoutParams(layoutParams2);
            }

            homeBinding.layoutOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.vB2cOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2cTrailer.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_b2b_pick))) {
            if (homeBinding.tvB2bOutbound.getVisibility() == View.VISIBLE) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) homeBinding.tvB2bOutbound.getLayoutParams();
                float weightSum = layoutParams.weight;
                layoutParams.weight = weightSum + 1;
                homeBinding.tvB2bOutbound.setLayoutParams(layoutParams);

                LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) homeBinding.vB2bOutbound.getLayoutParams();
                float weightSum2 = layoutParams2.weight;
                layoutParams2.weight = weightSum2 + 1;
                homeBinding.vB2bOutbound.setLayoutParams(layoutParams2);
            }

            homeBinding.layoutOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2bOutbound.setVisibility(View.VISIBLE);
            homeBinding.vB2bOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2bPick.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_b2b_trailer))) {
            if (homeBinding.tvB2bOutbound.getVisibility() == View.VISIBLE) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) homeBinding.tvB2bOutbound.getLayoutParams();
                float weightSum = layoutParams.weight;
                layoutParams.weight = weightSum + 1;
                homeBinding.tvB2bOutbound.setLayoutParams(layoutParams);

                LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) homeBinding.vB2bOutbound.getLayoutParams();
                float weightSum2 = layoutParams2.weight;
                layoutParams2.weight = weightSum2 + 1;
                homeBinding.vB2bOutbound.setLayoutParams(layoutParams2);
            }

            homeBinding.layoutOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2bOutbound.setVisibility(View.VISIBLE);
            homeBinding.vB2bOutbound.setVisibility(View.VISIBLE);
            homeBinding.tvB2bTrailer.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_returns_pre_process))) {
            homeBinding.layoutReturns.setVisibility(View.VISIBLE);
            homeBinding.tvPreprocess.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_returns_final_process))) {
            homeBinding.layoutReturns.setVisibility(View.VISIBLE);
            homeBinding.tvFinalprocess.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_outbound_returns_putaway))) {
            homeBinding.layoutReturns.setVisibility(View.VISIBLE);
            homeBinding.tvReturnsPutaway.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_manage_cycle_count))) {
            homeBinding.layoutManage.setVisibility(View.VISIBLE);
            homeBinding.tvCyclecount.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_manage_transfer))) {
            homeBinding.layoutManage.setVisibility(View.VISIBLE);
            homeBinding.tvTransfer.setVisibility(View.VISIBLE);
        } else if (authorize.getCode().equals(getString(R.string.pda_manage_adjust))) {
            homeBinding.layoutManage.setVisibility(View.VISIBLE);
            homeBinding.tvAdjust.setVisibility(View.VISIBLE);
        }
    }

    public void onViewClicked(View view) {
        if (binding.slidingmenu.isOpen()) {
            binding.slidingmenu.toggleMenu();
            return;
        }
        switch (view.getId()) {
            case R.id.iv_mine://
                binding.slidingmenu.toggleMenu();
                break;
            case R.id.layout_search://查询
                AppRouter.showFragmentActivity(this, SearchActivity.class);
                break;
            case R.id.iv_news://任务
                homeBinding.tvNews.setUnreadCount(0);
                AppRouter.showFragmentActivity(this, NewsActivity.class);
                break;
            case R.id.tv_receiving://收货
                AppRouter.showFragmentActivity(this, CheckinActivity.class);
                break;
            case R.id.tv_tally://常规理货
                Bundle tallyBundle = new Bundle();
                tallyBundle.putInt("typ", 1);
                AppRouter.showFragmentActivity(this, TallyActivity.class, tallyBundle);
                break;
            case R.id.tv_damage://破损录入
                Bundle damageBundle = new Bundle();
                damageBundle.putInt("typ", 2);
                AppRouter.showFragmentActivity(this, TallyActivity.class, damageBundle);
                break;
            case R.id.tv_lpn_photo://LPN 图片
                AppRouter.showFragmentActivity(this, LPNPhotoActivity.class);
                break;
            case R.id.tv_putaway://上架
                homeBinding.tvTaskPutaway.setUnreadCount(0);
                AppRouter.showFragmentActivity(this, PutawayActivity.class);
                break;
            case R.id.tv_b2c_pick://拣货
                AppRouter.showFragmentActivity(this, B2CPickActivity.class);
                break;
            case R.id.tv_b2c_verify://拣货
                AppRouter.showFragmentActivity(this, B2CVerifyActivity.class);
                break;
            case R.id.tv_b2c_trailer://装车
                AppRouter.showFragmentActivity(this, B2CTrailerActivity.class);
                break;
            case R.id.tv_b2b_pick://b2b拣货
                AppRouter.showFragmentActivity(this, B2BPickActivity.class);
                break;
            case R.id.tv_b2b_trailer://b2b出库
                AppRouter.showFragmentActivity(this, B2BTrailerActivity.class);
                break;
            case R.id.tv_preprocess://退件预处理
                AppRouter.showFragmentActivity(this, PreprocessActivity.class);
                break;
            case R.id.tv_finalprocess://二次退件
                AppRouter.showFragmentActivity(this, FinalProcessActivity.class);
                break;
            case R.id.tv_returns_putaway://退件上架
                homeBinding.tvTaskReturnsPutaway.setUnreadCount(0);
                AppRouter.showFragmentActivity(this, ReturnsPutatayActivity.class);
                break;
            case R.id.tv_returns_trailer://退件装车
                AppRouter.showFragmentActivity(this, ReturnsTrailerActivity.class);
                break;
            case R.id.tv_cyclecount://盘点
                AppRouter.showFragmentActivity(this, CycleCountActivity.class);
                break;
            case R.id.tv_transfer://移库
                AppRouter.showFragmentActivity(this, TransferActivity.class);
                break;
            case R.id.tv_adjust://调整库存
                AppRouter.showFragmentActivity(this, AdjustActivity.class);
                break;
        }
    }

    private void setPickerView() {
        OptionsPickerView<UserEntity.WarehouseListDTO> mOptionsPickerView = new OptionsPickerView<>(this);
        // 设置数据
        mOptionsPickerView.setPicker(warehouseList);
        mOptionsPickerView.setSelectOptions(-1);
        mOptionsPickerView.setCancelTextColor(R.color.color_666666);
        mOptionsPickerView.setSubmitText("Confirm");
        mOptionsPickerView.setCancelText("Cancel");
        mOptionsPickerView.setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int option1, int option2, int option3) {
                UserEntity.WarehouseListDTO userWarehouse = warehouseList.get(option1);

                MyApplication.location = userWarehouse.getId() + "";
                PreferencesUtil.putString(mContext, Constant.location, userWarehouse.getId() + "");
                PreferencesUtil.putString(mContext, Constant.locationName, userWarehouse.getCode() + "");
                mineBinding.tvLocaion.setText(userWarehouse.getCode());
                mOptionsPickerView.dismiss();
            }
        });
        mOptionsPickerView.show();
    }

    private AlertDialog dialogLogout;

    private void showLogoutDialog() {
        dialogLogout = MyDialogUtil.getDialog(mContext, initLogoutDialogView(), Gravity.CENTER);
        dialogLogout.setCanceledOnTouchOutside(true);
        dialogLogout.show();
    }

    private View initLogoutDialogView() {
        DialogSkuMultipleHintBinding dialogBinding = DialogSkuMultipleHintBinding.inflate(getLayoutInflater());
        dialogBinding.tvTitle.setText("Tips");
        dialogBinding.tvContent.setText("Are you sure to log out?");
        dialogBinding.tvCancel.setVisibility(View.VISIBLE);
        dialogBinding.viewLine.setVisibility(View.VISIBLE);
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogLogout != null) {
                dialogLogout.dismiss();
            }
        });
        dialogBinding.tvConfirm.setText("Sure");
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            if (dialogLogout != null) {
                dialogLogout.dismiss();
            }
            MyApplication.token = "";
            PreferencesUtil.putString(this, Constant.location, "");
            PreferencesUtil.putString(this, Constant.token, "");
            PreferencesUtil.putBoolean(mContext, Constant.isManager, false);
            AppRouter.showFragmentActivity(this, LoginActivity.class);
            finish();
        });
        return dialogBinding.getRoot();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        viewModel.taskTips();
        OkHttpUtils.getInstance(mContext).getPdaPassword();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(Object object) {
        if (object instanceof String) {
            String str = (String) object;
            Log.e(TAG, "str:" + str);
            if (str.equalsIgnoreCase("logout")) {
                AppRouter.setLogin(this);
            }
        } else if (object instanceof PdaPassword) {
            if (PreferencesUtil.getBoolean(mContext, Constant.isManager)) {
                PdaPassword pdaPassword = (PdaPassword) object;
                String str = "Admin Password: ";//TextView所有字体
                int fstart = str.length();//文本中的关键字
                int fend = fstart + pdaPassword.getPassword().length();
                SpannableStringBuilder style = new SpannableStringBuilder(str + pdaPassword.getPassword());
                style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                mineBinding.tvPassword.setText(style);
                mineBinding.layoutPassword.setVisibility(View.VISIBLE);
            }
        } else if (object instanceof TaskQty) {
            TaskQty searchTaskQty = (TaskQty) object;
            int totalCount = searchTaskQty.getTaskCount();
            homeBinding.tvNews.setUnreadCount(totalCount);
            int putawayCount = searchTaskQty.getPutawayCount();
            homeBinding.tvTaskPutaway.setUnreadCount(putawayCount);
            int returnPutawayCount = searchTaskQty.getReturnPutawayCount();
            homeBinding.tvTaskReturnsPutaway.setUnreadCount(returnPutawayCount);
        } else if (object instanceof UpdateVersion) {//提示版本升级
            Log.e(TAG, "提示版本升级");
            startActivity(new Intent(this, VersionActivity.class));
        }
    }

    File apkfile;

    public void setApkFile(File file) {
        apkfile = file;
        installApk();
    }

    //7.在请求安装未知应用来源的权限后
    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 10086) {

            Uri packageURI = Uri.parse("package:com.app.twth");
//            Uri packageURI = Uri.parse("package:" + getPackageName());
            Log.e(TAG, "packageURI:" + packageURI);
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
            startActivityForResult(intent, 457);
        }
    }

    //8.在 startActivityForResult(intent,457);执行后
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 457) {
            if (Build.VERSION.SDK_INT >= 26) {
                if (getPackageManager().canRequestPackageInstalls()) {

                    installApk();
                } else {
                    ToastUtil.showToast("Installation permission is not enabled, installation failed!");
                }
            }
        } else if (requestCode == 1002) {
            if (!Settings.canDrawOverlays(this)) {
                //若未授权则请求权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1002);
            }
        }
    }

    //9.安装apk，适配android 7.0
    private void installApk() {
        if (apkfile == null) {
            Log.e(TAG, "1apkfile==null");
            apkfile = new File(getExternalCacheDir().getPath(), "twth.apk");
            Log.e(TAG, "apkfile:" + apkfile.getPath());
        }

        if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "com.app.twth.fileprovider", apkfile);
            Log.e(TAG, "apkUri:" + apkUri);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
